package com.czy.enchantmentvisualization.controller;

import com.czy.enchantmentvisualization.EnchantmentVisualizationApplication;
import com.czy.enchantmentvisualization.common.GeneralInformation;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

@RestController
@RequestMapping("/image")
public class ImageController {

    @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping("/{imageName}")
    public void getImage(@PathVariable String imageName) throws IOException {
        for (String img : GeneralInformation.imageList) {
            if (img.contains(imageName)) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletResponse response = requestAttributes.getResponse();
                ServletOutputStream outputStream = response.getOutputStream();
                InputStream inputStream = resourceLoader.getResource(img).getInputStream();

                IOUtils.copy(inputStream, outputStream);

                inputStream.close();
            }
        }
    }

}
